<?php namespace App\Http\Controllers\Api;

use App\Exceptions\WechatException;
use App\Files;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Images;
use App\User;
use App\Userinfo;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Requests_Exception;

class AuthController extends Controller
{
    private $wechat_base_url = 'https://api.weixin.qq.com/sns/jscode2session';

    public function wxLogin(Request $request){
        $AppId          = env("WEIXIN_KEY");
        $AppSecret      = env("WEIXIN_SECRET");
        $code           = $request->get("code");
        $signature      = $request->get("signature");
        $rawData        = $request->get("raw_data");

        $wechatLogin = new AuthController();
        $wx_request_url = $wechatLogin->wechat_base_url."?appid=".$AppId."&secret=".$AppSecret."&js_code=".$code."&grant_type=authorization_code";

        try{
            $result = \Requests::get($wx_request_url,array(),array());
        }catch (Requests_Exception $ex){
            throw new WechatException(WechatException::WeChatSignInFail,['message' => $ex->getMessage()]);
        }

        if (!$result->success) {
            return false;
        }

        $res = json_decode($result->body);

        if(isset($res->errcode) && !empty($res->errcode)){
            return response()->json(['level'=>'error','message'=>$res['errmsg'],"data"=>null]);
        }

        $openid      = $res->openid;
        $session_key = $res->session_key;

        // 数据签名校验
        $signature2 = sha1($rawData.$session_key);
        if ($signature != $signature2) {
            return response()->json(['level'=>'error','message'=>'获取失败']);
        }

        $wxInfo = json_decode($rawData,true);

        /** @var User $newUser */
        $newUser = User::whereWxOpenid($openid)->first();
        if(!$newUser) {
            $newUser = new User();
            $newUser->wx_openid = $openid;

            $newUser->wx_session_key = $session_key;
            $newUser->password = bcrypt('123456');
            $newUser->reg_ip = $request->ip();
            $newUser->reg_time = Carbon::now();
            $newUser->save();

            $headImgUrl = $wxInfo["avatarUrl"];

            $userInfo = new Userinfo();
            $userInfo->user_id = $newUser->id;
            $userInfo->nickname = $wxInfo["nickName"];
            $userInfo->sex = $wxInfo["gender"];
            $userInfo->province = $wxInfo["province"];
            $userInfo->city = $wxInfo["province"];
            $userInfo->save();

            /** @var Files $fileModel */
            $fileModel = FileManager::saveFileByWechatImg($headImgUrl);
            if ($fileModel) {
                $imageModel = Images::whereFileId($fileModel->id)->first();
                if (!$imageModel) {
                    $imageModel = new Images();
                    $imageModel->file_id = $fileModel->id;
                    $imageModel->img_name = 'wechat_img';
                    $imageModel->img_type = $fileModel->file_type;
                    $imageModel->save();

                    $userInfo->photo_id = $imageModel->id;
                    $userInfo->save();
                }
            }
        }else{
            $newUser->wx_session_key = $session_key;
            $newUser->save();
        }

        $token = CryptoJSAES::encrypt($openid,env('AES_KEY'));
        return response()->json(['level'=>"success","message"=>"获取成功","data"=>$token]);
    }
}